package com.atguigu.common.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * className: JwtHelper
 * description: jwt 工具类
 * date: 2023/4/15 0015-18:54
 * <p>
 * project: guigu-oa-parent
 * package: com.atguigu.common.jwt
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public final class JwtHelper {
    private static final long TOKEN_EXPIRATION = 365L * 24 * 60 * 60 * 1000;
    private static final String TOKEN_SIGN_KEY = "123456";

    /**
     * 根据用户 id 和用户名称 生成 token
     *
     * @param userId   {@link Long}
     * @param username {@link String}
     * @return {@link String}
     */
    public static String createToken(Long userId, String username) {
        return Jwts.builder()
                // 类目
                .setSubject("AUTH-USER")
                // 设置 token 有效时长
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                // 设置主体部分
                .claim("userId", userId)
                .claim("username", username)
                // 签名
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY)
                // 压缩
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 根据 token 获取用户 id
     *
     * @param token {@link String} token
     * @return {@link Long} userId
     */
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据 token 获取用户名
     *
     * @param token {@link String} token
     * @return {@link String} username
     */
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return "";
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(4L, "li4");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUsername(token));
    }
}
